<template>
  <el-scrollbar class="h-full">
    <el-card>
      <!-- 场景设置 -->
      <SettingItem title="场景" description="设置具体的场景，系统将执行相应的指令组合">
        <el-button type="primary" :icon="Plus" @click="showAddDialog"> 添加场景 </el-button>
      </SettingItem>

      <!-- 场景列表表格 -->
      <div class="mt-4">
        <el-table :data="sceneList" stripe style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="name" label="场景名称" width="200" />
          <el-table-column prop="orderIds" label="关联指令" min-width="250">
            <template #default="{ row }">
              <el-tag v-for="orderId in row.orderIds" :key="orderId" class="mr-1 mb-1" size="small">
                {{ getOrderName(orderId) }}
              </el-tag>
              <span v-if="!row.orderIds || row.orderIds.length === 0" class="text-gray-400">
                暂无关联指令
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="场景描述"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <el-empty v-if="!tableLoading && sceneList.length === 0" description="暂无场景数据" />
        <!-- 分页 -->
        <div class="flex justify-center mt-4">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑场景对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增场景' : '编辑场景'"
      v-model="addDialogVisible"
      width="700px"
      destroy-on-close
      :before-close="handleCloseAddDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场景名称" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入场景名称，例如：回家模式"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场景状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择场景状态" style="width: 100%">
                <el-option label="启用" value="ACTIVE" />
                <el-option label="禁用" value="INACTIVE" />
                <el-option label="维护中" value="MAINTENANCE" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="关联指令" prop="orderIds">
          <el-select
            v-model="formData.orderIds"
            multiple
            placeholder="请选择要关联的指令"
            style="width: 100%"
            collapse-tags
            collapse-tags-tooltip
          >
            <el-option
              v-for="order in orderOptions"
              :key="order.id"
              :label="order.name"
              :value="order.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="场景描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入场景描述，例如：回家后自动执行的指令组合"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ dialogType === 'add' ? '添加' : '更新' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import SettingItem from '@/components/common/SettingItem.vue'
import { createScene, fetchList, updateScene, deleteScene } from '@/api/scene'
import { useUserStore } from '../../../store/user'

const userStore = useUserStore()

// 表格数据
const sceneList = ref([])
const tableLoading = ref(false)
const submitLoading = ref(false)

// 分页数据
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

// 指令选项
const orderOptions = ref([])

// 对话框相关
const dialogType = ref<'add' | 'edit'>('add')
const addDialogVisible = ref(false)
const formRef = ref()

// 表单数据结构
const defaultForm = {
  id: null,
  userId: null,
  name: '',
  orderIds: [],
  status: 'ACTIVE',
  description: ''
}
const formData = ref({ ...defaultForm })

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入场景名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择场景状态', trigger: 'change' }],
  description: [{ required: true, message: '请输入场景描述', trigger: 'blur' }]
}

/**
 * 获取场景列表
 */
const getSceneList = async () => {
  try {
    tableLoading.value = true
    const response = await fetchList({
      page: pagination.value.page,
      limit: pagination.value.limit,
      userId: userStore.userId
    })

    if (response.data?.list) {
      sceneList.value = response.data.list
      pagination.value.total = response.data.total || 0
    } else {
      sceneList.value = response.data || []
      pagination.value.total = sceneList.value.length
    }
  } catch (error) {
    console.error('获取场景列表失败:', error)
    ElMessage.error('获取场景列表失败')
  } finally {
    tableLoading.value = false
  }
}

/**
 * 根据指令ID获取指令名称
 */
const getOrderName = (orderId: number) => {
  const order = orderOptions.value.find((item: any) => item.id === orderId)
  return order?.name || `指令${orderId}`
}

/**
 * 显示新增场景对话框
 */
const showAddDialog = () => {
  formData.value = { ...defaultForm }
  dialogType.value = 'add'
  addDialogVisible.value = true
}

/**
 * 编辑场景
 */
const handleEdit = (row: any) => {
  formData.value = {
    ...row,
    orderIds: Array.isArray(row.orderIds) ? row.orderIds : []
  }
  dialogType.value = 'edit'
  addDialogVisible.value = true
}

/**
 * 删除场景
 */
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除场景"${row.name}"吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteScene(row.id)
    ElMessage.success('删除成功')
    await getSceneList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 关闭场景对话框
 */
const handleCloseAddDialog = () => {
  formData.value = { ...defaultForm }
  if (formRef.value) {
    formRef.value.resetFields()
  }
  addDialogVisible.value = false
}

/**
 * 添加/更新场景
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: any) => {
    if (!valid) return

    try {
      submitLoading.value = true
      formData.value.userId = userStore.userId

      if (dialogType.value === 'add') {
        await createScene(formData.value)
        ElMessage.success('添加成功')
      } else {
        await updateScene(formData.value)
        ElMessage.success('更新成功')
      }

      handleCloseAddDialog()
      await getSceneList()
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
    } finally {
      submitLoading.value = false
    }
  })
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1
  getSceneList()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  getSceneList()
}

/**
 * 获取状态标签样式
 */
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: 'success',
    INACTIVE: 'info',
    MAINTENANCE: 'warning'
  }
  return statusMap[status] || 'info'
}

/**
 * 获取状态标签文本
 */
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    ACTIVE: '启用',
    INACTIVE: '禁用',
    MAINTENANCE: '维护中'
  }
  return statusMap[status] || status
}

// 组件挂载时获取数据
onMounted(() => {
  getSceneList()
})
</script>

<style scoped lang="scss">
.dialog-footer {
  @apply flex justify-end gap-2;
}

.el-table {
  margin-top: 16px;
}

.el-tag {
  font-size: 12px;
}
</style>
